//
//  RHBatchSolarkVPPConfigVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/5/19.
//

#import "RHBatchSolarkVPPConfigVC.h"
#import "SYChartTool.h"
#import "ZYSwitch.h"
#import "KWTMGRNSettingSyncVC.h"
#import "SettingOptionController.h"
#import "RHDeviceModel.h"
#import "RHEndPointModel.h"
#import "PasswordVerifyController.h"
#import "RHTools.h"
#import "RHSolarkSettingChgTimeCell.h"
#import "RHSolarkSettingEditTimeVC.h"
#import "WSDatePickerView.h"
#import "NetworkAgent.h"
#import "RHSolarkSettingModel.h"

@interface RHBatchSolarkVPPConfigVC ()
<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *dataArr;

@property (nonatomic ,strong) NSMutableArray *paraSectionArr;//每组的参数

@property (nonatomic, strong) NSDictionary *configDic;//之前保存的配置

@property (nonatomic, copy) NSString *invType;//逆变器类型
@end

@implementation RHBatchSolarkVPPConfigVC
-(instancetype)initWithInvType:(NSString*)invType
{
    if (self = [super init]) {
        _invType = invType;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"充放电配置".rh_localized;
    self.paraSectionArr = [NSMutableArray array];
    [self setupUI];
    [self getParamConfig];
}

- (void)setupUI{
    kWeakSelf;
    NSString *jsonFile = @"setting_me_solark_60k_chg";
    if ([self.invType isEqualToString:InvType_Sol_Ark_30K_3P_208V]) {
        jsonFile = @"setting_me_solark_30k_chg";
    }
    NSArray *arr = [SYChartTool loadJsonFileWithName:jsonFile];
    self.dataArr = [NSArray yy_modelArrayWithClass:[RHSolarkSettingModel class] json:arr];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:kCOLOR_HEX(@"#F0F5FF")];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setSeparatorColor:UIColor.clearColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHSolarkSettingChgTimeCell class] forCellReuseIdentifier:@"RHSolarkSettingChgTimeCell"];
    _tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 8)];
    _tableView.tableFooterView = [self footerView];
    [self.view addSubview:_tableView];
     
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.bottom.mas_offset(0);
        make.top.mas_offset(0);
    }];
    
    self.tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    
    [self.tableView addHeaderRefresh:^{
        [weakSelf getParamConfig];
    }];
    
    
}


#pragma mark ------ 1.获取保存的配置
-(void)getParamConfig
{
    [QMUITips showLoadingInView:kAppWindow];
    NSInteger configType = 4;
    if ([self.invType isEqualToString:InvType_Sol_Ark_60K_3P_480V]) {
        configType = 5;
    }
    [BaseModel startGetWithCompletionAPIKey:H_getPlantGroupForceConfig argument:@{@"configType":@(configType)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if (resultModel.code == 200) {
            NSDictionary *dataDic = request.responseJSONObject[@"data"];
            if (dataDic[@"strategy"]) {
                NSDictionary *dic = [dataDic[@"strategy"] jsonStringToDictionary];
                self.configDic = dic;
                NSMutableDictionary *mtbDic = [NSMutableDictionary dictionary];
                if (![dic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                if(dic[@"protocolBody"]){
                    NSArray *dicArr = dic[@"protocolBody"][@"commandParamList"];
                    [dicArr enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull paraDic, NSUInteger idx, BOOL * _Nonnull stop) {
                        [mtbDic setObject:ValidNullData(paraDic[@"value"]) forKey:ValidNullData(paraDic[@"paramName"])];
                    }];
                    [self readDefult:mtbDic];
                    [self.tableView reloadData];
                }
                
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}

//读取默认值
- (void)readDefult:(NSDictionary *)dic{
    [self.dataArr enumerateObjectsUsingBlock:^(RHSolarkSettingModel*  _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
       
        [model readDefult:dic];
        [model.rows enumerateObjectsUsingBlock:^(RHSolarkSettingModel * _Nonnull rowModel, NSUInteger idx, BOOL * _Nonnull stop_row) {
            //现在设备上传的北京时间,要转成本地时间显示
            if ([rowModel.type isEqualToString:@"date"]) {
                if (rowModel.content.length>6) {
                    rowModel.content = [NSDate beiJinTimeConvertToLocalTime:rowModel.content];
                    *stop_row = YES;
                }
            }
        }];
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0||section == 1) {
        return 20;
    }
    
    return 60;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0||section == 1) {
        UIView *headV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 20)];
        headV.backgroundColor = kCOLOR_HEX(@"#F0F5FF");
        UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 10, kUI_WINDOW_W-30, 10)];
        bgView.backgroundColor = UIColor.whiteColor;
        bgView.layer.cornerRadius = 8;
        bgView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
        bgView.layer.masksToBounds = YES;
        [headV addSubview:bgView];
        return headV;
    }
    
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 60)];
    headerView.backgroundColor = kCOLOR_HEX(@"#F0F5FF");
    RHSolarkSettingModel *sectionModel = self.dataArr[section];
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 15, kUI_WINDOW_W-30, 45)];
    bgView.backgroundColor = UIColor.whiteColor;
    bgView.layer.cornerRadius = 8;
    bgView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    bgView.layer.masksToBounds = YES;
    [headerView addSubview:bgView];
    
    QMUILabel *titleLab = [QMUILabel labelWithText:sectionModel.sectionTitle.rh_localized font:kSYSTEMFONT(16) textColor:kCOLOR_HEX(@"#171A1D")];
    [bgView addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.centerY.mas_offset(0);
    }];
    
    
    UIView *line = kView;
    line.backgroundColor = kCOLOR_HEX_A(@"#7E868E",0.2);
    [bgView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.offset(1);
    }];
    
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 10;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    kWeakSelf;
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 10)];
    footerView.backgroundColor = kCOLOR_HEX(@"#F0F5FF");
//    KWTMGRNSettingModel *sectionModel = self.dataArr[section];
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 0, kUI_WINDOW_W-30, 10)];
    bgView.backgroundColor = UIColor.whiteColor;
    bgView.layer.cornerRadius = 8;
    bgView.layer.maskedCorners = kCALayerMinXMaxYCorner|kCALayerMaxXMaxYCorner;
    bgView.layer.masksToBounds = YES;
    [footerView addSubview:bgView];
    
    
    return footerView;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    RHSolarkSettingModel *sectionModel = self.dataArr[section];
    return sectionModel.rows.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RHSolarkSettingModel *sectionModel = self.dataArr[indexPath.section];
    RHSolarkSettingModel *rowModel = sectionModel.rows[indexPath.row];
    if ([rowModel.type isEqualToString:@"date"]) {//系统时间校准
        RHSolarkSettingChgTimeCell *dateCell = [tableView dequeueReusableCellWithIdentifier:@"KWTMGRNSettingDateCell"];
        dateCell.model = rowModel;
        kWeakSelf;
        //时间选择
        dateCell.selectAction = ^(RHSolarkSettingModel * _Nonnull model) {
            [weakSelf dateAction:model];
        };
        
        dateCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return dateCell;
    }
    if ([rowModel.type isEqualToString:@"time"]) {//充放电时段设置
        RHSolarkSettingChgTimeCell *settingCell = [tableView dequeueReusableCellWithIdentifier:@"RHSolarkSettingChgTimeCell"];
        rowModel.rowTitle = [NSString stringWithFormat:@"%@ %ld",@"时段".rh_localized,indexPath.row+1];
        settingCell.model = rowModel;
        kWeakSelf;
        settingCell.selectAction = ^(RHSolarkSettingModel * _Nonnull model) {
            [weakSelf editChargeDischargeInfo:model index:indexPath.row+1];
        };
        settingCell.commitAction = ^(RHSolarkSettingModel * _Nonnull model) {
            [weakSelf checkParaEnableStatus];
        };
        settingCell.readAction = ^(RHSolarkSettingModel * _Nonnull model) {
//            [weakSelf readParamData];
        };
        settingCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return settingCell;
    }
    return [UITableViewCell new];
}

#pragma mark -------- 充放电时间段选择
-(void)editChargeDischargeInfo:(RHSolarkSettingModel*)model index:(NSInteger)index
{
    kWeakSelf;
    RHSolarkSettingEditTimeVC *editVC = [[RHSolarkSettingEditTimeVC alloc]init];
    editVC.index = index;
    editVC.model = model;
    editVC.sureBlock = ^{
        //编辑了开始时间,上一组的结束时间要跟着变; 编辑了结束时间,下一组的开始时间要跟着变
        [weakSelf.dataArr enumerateObjectsUsingBlock:^(RHSolarkSettingModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
            [sectionModel.rows enumerateObjectsUsingBlock:^(RHSolarkSettingModel * _Nonnull rowModel, NSUInteger idx, BOOL * _Nonnull stop) {
                [rowModel.items enumerateObjectsUsingBlock:^(RHSolarkSettingModel * _Nonnull itemModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    [model.items enumerateObjectsUsingBlock:^(RHSolarkSettingModel * _Nonnull editModel, NSUInteger idx, BOOL * _Nonnull stop) {
                        if ([itemModel.key isEqualToString:editModel.key]) {
                            itemModel.content = editModel.content;
                        }
                    }];
                    
                }];
            }];
        }];
        [weakSelf.tableView reloadData];
    };
    [self.navigationController pushViewController:editVC animated:YES];
}

#pragma mark -------- 选择时间
- (void)dateAction:(RHSolarkSettingModel *)settingModel  {
    
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDayHourMinuteSecond CompleteBlock:^(NSDate *selectDate) {
        NSString *dateFormatStr = @"yyyy/MM/dd HH:mm:ss";
        NSString *currentDate = [selectDate stringWithFormat: dateFormatStr];
        settingModel.content = currentDate;
        [self.tableView reloadData];
    }];
    datePickerV.dateLabelColor = FontColor(@"#3ECE80");//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    [datePickerV show];
}

#pragma mark ------ 选择
-(void)selectAction:(RHSolarkSettingModel*)model
{
    kWeakSelf;
    SettingOptionController *vc = [[SettingOptionController alloc] initWithData:model.selectList];
    [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
    
    vc.curTextValue = [model.content integerValue];
   
    vc.selectBlock = ^(NSInteger index) {
        DevSettingOptionModel *select_model = model.selectList[index];
        model.enumText = select_model.text;//存要显示的内容
        model.content = [NSString stringWithFormat:@"%ld",select_model.textValue];//存下标
        [weakSelf.tableView reloadData];
    };
}


#pragma mark -------- 提交参数前 判断是否选择了Solark逆变器的分组
-(void)checkParaEnableStatus
{
  
    [self commitAction];

}

#pragma mark -------- 提交参数前 密码校验
-(void)commitAction
{
    
//    if (Password_Check) {
//        PasswordVerifyController *vc = [[PasswordVerifyController alloc] init];
//        [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
//        
//        kWeakSelf;
//        vc.callBackBlock = ^(NSString * _Nonnull password) {
//                    NSDictionary *dic = [RHTools getAccountInfo];
//                    if ([SafeStr(dic[@"password"]) isEqualToString:password]) {
//                        BOOL result = [weakSelf createSectionSetPara];
//                        if (result == NO) return;//校验不过
//                       
//                        [weakSelf devParamsSetFromNetwork];
//                    }else{
//                        [QMUITips showInfo:@"密码错误".rh_localized];
//                    }
//        };
//    }else{
//        BOOL result = [self createSectionSetPara];
//        if (result == NO) return;//校验不过
//        [self devParamsSetFromNetwork];
//    }
    BOOL result = [self createSectionSetPara];
    if (result == NO) return;//校验不过
    [self devParamsSetFromNetwork];
    
}

//把设置指令分组下发   没有值的参数不下发
-(BOOL)createSectionSetPara
{
 
    [self.paraSectionArr removeAllObjects];
   
    __block BOOL isCheckOK = YES;//校验是否通过
    
    [self.dataArr enumerateObjectsUsingBlock:^(RHSolarkSettingModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
        
        //上一时间段的结束时间,如果有就比较(当前时间段的开始时间要大于上一段的结束时间)
        __block NSString* lastEndTime;
        __block NSInteger lastEndTimeIndex = 0;
        [sectionModel.rows enumerateObjectsUsingBlock:^(RHSolarkSettingModel * _Nonnull rowModel, NSUInteger rowIdx, BOOL * _Nonnull stop_row) {
            //系统设置不提交(单独提交)
            if ([rowModel.type isEqualToString:@"date"]) {
                return;
            }
            //工作模式 充电使能
            if ([rowModel.type isEqualToString:@"switch"]||[rowModel.type isEqualToString:@"select"]) {
                if (rowModel.content.length == 0) {
                    return;
                }
                NSMutableDictionary *textDic = [NSMutableDictionary dictionary];
                [textDic setObject:rowModel.format forKey:@"dataType"];
                [textDic setObject:rowModel.key forKey:@"paramName"];
                [textDic setObject:rowModel.content forKey:@"value"];
                [textDic setObject:@(rowModel.regAddr) forKey:@"regAddr"];
                [textDic setObject:@(rowModel.num) forKey:@"num"];
                [textDic setObject:@(rowModel.offset) forKey:@"offset"];
                
                [self.paraSectionArr addObject:textDic];
            }
            
            //时间段设置
            if ([rowModel.type isEqualToString:@"time"]) {

                __block NSString *startTime;//每段的开始时间
                __block NSString *endTime;  //每段的结束时间
               
                [rowModel.items enumerateObjectsUsingBlock:^(RHSolarkSettingModel * _Nonnull itemModel, NSUInteger idx, BOOL * _Nonnull stop_item) {
                    
                    if (itemModel.content.length == 0) {
                        return;
                    }
                    
                    NSMutableDictionary *itemDic = [NSMutableDictionary dictionary];
                    [itemDic setObject:itemModel.format forKey:@"dataType"];
                    [itemDic setObject:itemModel.key forKey:@"paramName"];
                    [itemDic setObject:ValidNullData(itemModel.content) forKey:@"value"];
                    [itemDic setObject:@(itemModel.regAddr) forKey:@"regAddr"];
                    [itemDic setObject:@(itemModel.num) forKey:@"num"];
                    [itemDic setObject:@(itemModel.offset) forKey:@"offset"];
                    
                    if ([itemModel.type isEqualToString:@"number"]) {
                        NSInteger contentValue = [itemModel.content integerValue];
                        if (itemModel.ratio) {
                            NSDecimalNumber *A = [NSDecimalNumber decimalNumberWithString:ValidNullDataToString(itemModel.content, @"0")];
                            NSDecimalNumber *B = [NSDecimalNumber decimalNumberWithString:itemModel.ratio];
                            NSDecimalNumber *result = [A decimalNumberByMultiplyingBy:B];
                            contentValue = [result integerValue];
                        }
                        if(itemModel.minValue){
                            if(contentValue<[itemModel.minValue integerValue]){//开关打开的情况才判断
                                if([itemModel.key containsString:@"Battery_Cut_Off_SOC"]){
                                    [QMUITips showInfo:[NSString stringWithFormat:@"时段%ld SOC不能小于%@",rowIdx+1,itemModel.minValue]];
                                }else{
                                    [QMUITips showInfo:[NSString stringWithFormat:@"时段%ld 电流不能小于%@",rowIdx+1,itemModel.minValue]];
                                }
                                isCheckOK = NO;
                                *stop_row = YES;
                                *stop_item = YES;
                                return;
                            }
                           
                        }
                        if (itemModel.maxValue) {
                            if(contentValue>[itemModel.maxValue integerValue]){
                                if([itemModel.key containsString:@"Battery_Power"]){
                                    [QMUITips showInfo:[NSString stringWithFormat:@"时段%ld SOC不能大于%@",rowIdx+1,itemModel.maxValue]];
                                }else{
                                    [QMUITips showInfo:[NSString stringWithFormat:@"时段%ld 电流不能大于%@",rowIdx+1,itemModel.maxValue]];
                                }
                                isCheckOK = NO;
                                *stop_row = YES;
                                *stop_item = YES;
                                return;
                            }
                        }
                    }
                    
                    //时间  结束时间是下一段的开始时间   结束时间不用提交
                    NSMutableDictionary *endTimeDic;
                    if ([itemModel.type isEqualToString:@"date"]) {
                        NSString *chg_startTimeKey_H = [NSString stringWithFormat:@"TOU_Time_%ld_Hour",rowIdx+1];
                        NSString *chg_startTimeKey_M = [NSString stringWithFormat:@"TOU_Time_%ld_Minute",rowIdx+1];
                       
                        //过滤结束时间
                        NSString *chg_endTimeKey_H = [NSString stringWithFormat:@"TOU_Time_%ld_Hour",rowIdx+1+1];
                        if ([itemModel.key isEqualToString:chg_endTimeKey_H]) {
                            return;
                        }
                        //最后一组的结束时间
                        if (rowIdx == 5) {
                            if ([itemModel.key isEqualToString:@"TOU_Time_1_Hour"]) {
                                return;
                            }
                        }
                       
                        NSLog(@"---->item key:%@  rowindex:%ld  itemIndex:%ld",itemModel.key,rowIdx,idx);
                        //充电开始时间 小时,分钟
                        if ([itemModel.key isEqualToString:chg_startTimeKey_H]) {
                            NSArray *timeArr = [itemModel.content componentsSeparatedByString:@":"];
                            NSInteger start_hour = [[timeArr firstObject]integerValue];
                            NSInteger start_minute = [[timeArr lastObject]integerValue];
                            [itemDic setObject:@(start_hour) forKey:@"value"];
                            //开始时间的分钟,先从小时的复制一份,寄存器地址加1
                            endTimeDic = [NSMutableDictionary dictionaryWithDictionary:itemDic];
                            [endTimeDic setObject:@(start_minute) forKey:@"value"];
                            [endTimeDic setObject:@(itemModel.regAddr+1) forKey:@"regAddr"];
                            [endTimeDic setObject:chg_startTimeKey_M forKey:@"paramName"];
                           
                            //作时间比较用
                            startTime = [NSString stringWithFormat:@"%02ld%02ld",start_hour,start_minute];
                        }
                       
                        
                    }
                    [self.paraSectionArr addObject:itemDic];
                    if (endTimeDic.allKeys.count>0) {
                        //加入开始或者结束时间的分钟数
                        [self.paraSectionArr addObject:endTimeDic];
                    }
                    //判断结束时间是否大于开始时间
                    NSString *startTime_key = [NSString stringWithFormat:@"TOU_Time_%ld_Hour",rowIdx+1];
                    NSString *endTime_key   = [NSString stringWithFormat:@"TOU_Time_%ld_Hour",rowIdx+1+1];
                    if (idx == 5) {//最后一个
                        endTime_key = @"TOU_Time_1_Hour";
                    }
                    if ([itemModel.key isEqualToString:startTime_key]&&itemModel.content.length>0) {
                        //开始时间
                        startTime = [itemModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                        RHSolarkSettingModel  *endTimeModel = [rowModel.items safeObjectAtIndex:idx+1];
                        if ([endTimeModel.key isEqualToString:endTime_key]&&endTimeModel.content.length>0) {
                            //结束时间
                            endTime = [endTimeModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                        }
                        
                        //判断当前开始时间是否大于上一段结束时间 如果两个是00:00的话不判断
                        BOOL bothZero = ([startTime integerValue]==0)&&([endTime integerValue]==0);
                        if (startTime.length>0 && lastEndTime.length>0) {
                            if (([startTime integerValue]<[lastEndTime integerValue])&&(!bothZero)) {
                                [QMUITips showInfo:[NSString stringWithFormat:@"时段%ld开始时间必须大于或等于时段%ld结束时间".rh_localized,rowIdx+1,lastEndTimeIndex+1]];
                                isCheckOK = NO;
                                return;
                            }
                        }
                    }
                    if ([itemModel.key isEqualToString:endTime_key]&&itemModel.content.length>0) {
                        endTime = [itemModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                        //上一段时间是00:00 - 00:00的话不比较
                        if ([endTime integerValue] != 0) {
                            lastEndTime = endTime;//保存上一时间段的结束时间(有时的情况下)
                            lastEndTimeIndex = rowIdx;
                        }
                    }
                }];
             
                
                if (startTime || endTime) {//如果一组里有一个时间填了,就比较,都没填的话不比较
                    if (([endTime integerValue] <= [startTime integerValue])&&([startTime integerValue]!=0)) {//两个都是00:00的就不比较
                        
                        if (rowIdx != 5) {//最一段不比较
                            isCheckOK = NO;
                            [QMUITips showInfo:[NSString stringWithFormat:@"时段%ld结束时间必须大于开始时间".rh_localized,rowIdx+1]];
                        }
                       
                    }
                    
                    //最后一段时间  结束时间要小于开始时间
                }
            }
            
        }];
        
        
       
        
    }];
    
    //如果没有填写时间段参数
    if(self.paraSectionArr.count==0){
        [QMUITips showInfo:@"参数不完整".rh_localized];
        isCheckOK = NO;
    }
    
    //校验不通过不提交
    if (isCheckOK == NO) {
        return NO;
    }
        
    //---------一次性下发------
    
    
    return YES;
}



#pragma mark ------ 保存参数配置
- (void)devParamsSetFromNetwork{
    
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    
    //全部参数一次性给到后台 , 不需要填端点sn参数,因为获取不到
    [paraListArr addObjectsFromArray:self.paraSectionArr];

    if (paraListArr.count == 0) {
        return;
    }
    
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:15];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDictionary *headContent = @{
        @"cmdId": randomStr,
        @"paramCount":@(paraListArr.count),
        @"messageType": @(1),//下行
        @"namespace": @"ParamSetSingle",
        @"payloadVersion": @(1),
        @"timestamp": @((NSInteger)interval)
      };
    
    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    NSDictionary *para = @{@"protocolHead":headContent,
                           @"protocolBody":bodyDic};
    NSString *paraStr = [para yy_modelToJSONString];
    NSString *configType = @"4";
    if ([self.invType isEqualToString:InvType_Sol_Ark_60K_3P_480V]) {
        configType = @"5";
    }
    NSDictionary *requestPara = @{
        @"configType":configType,//1.强制充放电 2.233  3.S40K  4.solark
        @"strategy":paraStr
    };
    
    [QMUITips showLoading:@"保存中...".rh_localized inView:kApplication.keyWindow];
    
    [BaseModel startWithCompletionAPIKey:H_savePlantGroupForceConfig argument:requestPara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            [QMUITips showSucceed:@"保存完成".rh_localized inView:self.view hideAfterDelay:1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        }
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
    
    }];
}




-(UIView*)footerView{
    kWeakSelf;
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 80)];
    
    QMUIButton *commitBtn = [[QMUIButton alloc]init];
    [commitBtn setTitle:@"提交".rh_localized forState:UIControlStateNormal];
    [commitBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [commitBtn setCornerRadius:8];
    [commitBtn setBackgroundColor:CMainColorGreen];
    [footer addSubview:commitBtn];
    [commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.height.offset(45);
        make.right.mas_offset(-15);
        make.centerY.mas_offset(0);
    }];
    
    
    [[commitBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf checkParaEnableStatus];
    }];
    
 
    return footer;
}



@end
